#include "Beep.h"

void Beep_Init(void)
{
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOF, ENABLE);
	
	GPIO_InitTypeDef GPIO_InitStructure;
	GPIO_InitStructure.GPIO_Mode 	= GPIO_Mode_Out_PP;	//推挽输出
	GPIO_InitStructure.GPIO_Pin 	= GPIO_Pin_0;
	GPIO_InitStructure.GPIO_Speed 	= GPIO_Speed_10MHz;
	GPIO_Init(GPIOF, &GPIO_InitStructure);
	
	GPIO_SetBits(GPIOF, GPIO_Pin_0);	//置高，蜂鸣器不响
}

void TIM_UserConfig (uint16_t Period, uint16_t Prescaler)
{
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1, ENABLE);
	
	TIM_TimeBaseInitTypeDef TIM_InitStructure;
	TIM_InitStructure.TIM_Period = Period;
	TIM_InitStructure.TIM_Prescaler = Prescaler;
	TIM_InitStructure.TIM_ClockDivision = TIM_CKD_DIV1;	//不分割时钟
	TIM_InitStructure.TIM_CounterMode = TIM_CounterMode_Up;	//向上计数
	TIM_InitStructure.TIM_RepetitionCounter = 0;	//重复计数次数，就是计数溢出即申请中断
	TIM_TimeBaseInit(TIM1, &TIM_InitStructure);	//初始化定时器
	
	TIM_ClearITPendingBit(TIM1, TIM_IT_Update);//清除 TIM1 的中断待处理位，先清除，再开启中断
	TIM_ITConfig(TIM1, TIM_IT_Update | TIM_IT_Trigger, ENABLE);//开启计数器中断（定时器1，计数|触发中断源，使能）
	TIM_Cmd(TIM1, ENABLE);//使能计数器
	
	NVIC_InitTypeDef NVIC_InitStructure;
	NVIC_PriorityGroupConfig(NVIC_PriorityGroup_0);	//设置中断分组0，主优先级0，抢占优先级3
	NVIC_InitStructure.NVIC_IRQChannel = TIM1_UP_IRQn;//中断入口
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3;
	NVIC_Init(&NVIC_InitStructure);
	
}

void TIM1_UP_IRQHandler(void)
{
	//获取中断状态
	if( TIM_GetITStatus(TIM1, TIM_IT_Update) != RESET )	//只要不等于0，就代表进来中断了
	{
		GPIO_WriteBit(GPIOF, GPIO_Pin_0, (BitAction)(!GPIO_ReadOutputDataBit(GPIOF, GPIO_Pin_0)));
		//进入中断，先把这个TIM_IT_Update清零
		TIM_ClearITPendingBit(TIM1, TIM_IT_Update);
	}
}
